package cc.customer.myCustomer.services.impl;

import cc.customer.common.domain.ResponseBo;
import cc.customer.common.service.impl.BaseService;
import cc.customer.common.utils.Constant;
import cc.customer.common.utils.DateUtil;
import cc.customer.common.utils.FebsUtil;
import cc.customer.common.utils.Utils;
import cc.customer.cusDynamic.domain.CusDynamic;
import cc.customer.cusDynamic.services.CusDynamicService;
import cc.customer.myCustomer.damain.CusResource;
import cc.customer.myCustomer.damain.MyCustomer;
import cc.customer.myCustomer.dao.CusResourceMapper;
import cc.customer.myCustomer.dao.MyCustomerMapper;
import cc.customer.myCustomer.services.PerSonServices;
import cc.customer.rabbit.domain.CconvNotice;
import cc.customer.system.domain.MyUser;
import cc.customer.system.service.UserService;
import cc.customer.utils.AutonCusInfo;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public class PerSonServicesImpl extends BaseService<MyCustomer> implements PerSonServices {

    @Autowired
    private CusResourceMapper cusResourceMapper;
    @Autowired
    private MyCustomerMapper mcsMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private UserService userMapper;
    @Autowired
    private CusDynamicService cusDynamicService;


    /**批量增加我的客户**/
    @Override
    @Transactional
    public ResponseBo batchAddPersonCus(List<MyCustomer> list) throws Exception{
        try {
            int num = 0;
            List<MyCustomer> myCustomers = new ArrayList<>();
            for (MyCustomer myCust:list){
                myCustomers.add(myCust);
                if(myCustomers.size()>300){
                    int bactNum = mcsMapper.insertList(myCustomers);
                    num += bactNum;
                    myCustomers.clear();
                }
            }
            if(!myCustomers.isEmpty()){
                int numlast = mcsMapper.insertList(myCustomers);
                num += numlast;
            }
            return ResponseBo.ok(num);
        }catch (Exception e){
            e.printStackTrace();
            throw  new RuntimeException();
        }
    }
    /**新增我的客户列表*/
    @Override
    public ResponseBo addMyCustomer(MyCustomer customer){
        try {
            String moblie = customer.getMyCusMobile();
            if (!StringUtils.isEmpty(moblie)){
                Boolean ble = FebsUtil.isPhoneNo(moblie);
                if(!ble){
                    return ResponseBo.error("请填写正确格式的手机号");
                }
                CusResource iscus = cusResourceMapper.selectByMobile(moblie);
                if(iscus!=null){
                    String receiver = iscus.getReceiver();
                    String shares = iscus.getSharcus();
                    String uuid = iscus.getUuid();
                    String creator = customer.getMyCusCreator();
                    if("2".equals(iscus.getDelstatus())){
                        String newReceiver = customer.getMyCusCreator();
                        MyCustomer cus = new MyCustomer();
                        cus.setMyCusName(customer.getMyCusName());
                        cus.setMyCusReceiver(newReceiver);
                        cus.setMyCusUuid(uuid);
                        mcsMapper.updateReceiverByUid(cus);
                        return ResponseBo.ok("新增成功");
                    }else if(receiver.equals(creator)){
                        return ResponseBo.ok("myself",iscus);
                    }else if(!"".equals(shares)&&shares!=null){
                        if(shares.contains(creator)){
                            return ResponseBo.ok("myself",iscus);
                        }
                        return ResponseBo.ok("客户重复",iscus);
                    }else{
                        return ResponseBo.ok("客户重复",iscus);
                    }
                }else{
                    mcsMapper.insert(customer);
                    return ResponseBo.ok("新增成功");
                }
            }else{
                mcsMapper.insert(customer);
                return ResponseBo.ok("新增成功");
            }
        }catch (Exception e){
            e.printStackTrace();
            return ResponseBo.error("新增失败，请联系网站管理员！");
        }
    }

    /**客户重复 申请共享*/
    @Override
    public ResponseBo shenqingShare(MyUser user, String uuid, String reid, String content, String name){
        try{
            CconvNotice notice = new CconvNotice();
            notice.setcConvSession(Utils.getUUID());
            notice.setcConvTime(DateUtil.getCurrentDate("yyyy-MM-dd HH:mm:ss"));
            notice.setcConvStatus("0");
            notice.setcConvType("1");
            notice.setcConvNType("4");
            notice.setcConvTitle("共享客户");
            notice.setcConvCreator(user.getUserUuid());
            String username = userService.findUserByUuids(reid).getUsername();
            notice.setcConvUsers(username);
            JSONObject json = new JSONObject();
            json.put("content","向您请求共享 "+name+" 给他");
            json.put("customerid",uuid);
            json.put("customername",name);
            json.put("custype","4");
            json.put("ntype","2");
            json.put("shencont",content);
            notice.setcConvCont(json.toJSONString());
            return ResponseBo.ok("申请客户共享成功,请等待回复。");
        }catch (Exception e){
            e.printStackTrace();
            return ResponseBo.error();
        }
    }

    /**查我的客户详情*/
    @Override
    public ResponseBo selectMyCusDetail(MyCustomer customer,MyUser user){
        try {
            MyCustomer cust = mcsMapper.selectMyCuatomerDetial(customer.getMyCusUuid());
            MyCustomer cus = AutonCusInfo.parsePerson(cust,user);
            if(cust!=null){
                return ResponseBo.ok("",cus);
            }else return ResponseBo.error("查询失败");
        }catch (Exception e){
            e.printStackTrace();
            return ResponseBo.error("查询失败");
        }
    }
    /**App查我的客户详情*/
    @Override
    public ResponseBo appSelectMyCusDetail(String myCusUuid,MyUser user){
        try {
            MyCustomer cust = mcsMapper.selectMyCuatomerDetial(myCusUuid);
            if(cust!=null){
                return ResponseBo.ok("",cust);
            }else return ResponseBo.errors("查询失败",cust);
        }catch (Exception e){
            e.printStackTrace();
            return ResponseBo.error("查询失败");
        }
    }
    /**获取我的客户的标签信息**/
    @Override
    public ResponseBo selectMyCuatomerLabel(String ids){
        try {
            MyCustomer cust = mcsMapper.selectMyCuatomerLabel(ids);
            if(cust!=null){
                return ResponseBo.ok("",cust);
            }else return ResponseBo.errors("查询失败",cust);
        }catch (Exception e){
            e.printStackTrace();
            return ResponseBo.error("查询失败");
        }
    }
    /**修改客户详情*/
    @Override
    public ResponseBo updateMyCusDetail(MyCustomer customer,MyUser user){
        try {
            int i = this.updateNotNull(customer);
            if(i>0){
                if (!StringUtils.isEmpty(customer.getMyCusStage())){
                    List<String> list = new ArrayList<>();
                    list.add(customer.getMyCusId()+"");
                    CusDynamic cus = new CusDynamic();
                    cus.setDyCreator(user.getUserUuid());
                    cus.setDyType(Constant.CUSTOMER_RECORD_STATAGES);
                    cus.setDySourceType("4");
                    String stta = AutonCusInfo.parseCustomerStage(customer.getMyCusStage());
                    cus.setDyContent(user.getNickname()+" 更改了客户阶段: "+stta);
                    cusDynamicService.inserDynamic(list,cus);
                }
                return ResponseBo.ok("更新成功");
            }else return ResponseBo.error("更新失败");
        }catch (Exception e){
            e.printStackTrace();
            return ResponseBo.error("更新失败");
        }
    }

    @Override
    public List<MyCustomer> selectMyCustomer(MyCustomer customer,MyUser myuser) {
        try {
            /**时间格式化选择**/
            String starttime = customer.getBeforeTime();
            if("7".equals(starttime)){
                Date week = DateUtil.addDays(new Date(),-7);
                String datestr = DateUtil.convert2String(week,"yyyy-MM-dd")+" 00:00:00";
                customer.setBeforeTime(datestr);
                customer.setAfterTime(DateUtil.getCurrentDate("yyyy-MM-dd")+" 23:59:59");
            }else if ("30".equals(starttime)){
                Date month = DateUtil.addDays(new Date(),-30);
                String datestr = DateUtil.convert2String(month,"yyyy-MM-dd")+" 00:00:00";
                customer.setBeforeTime(datestr);
                customer.setAfterTime(DateUtil.getCurrentDate("yyyy-MM-dd")+" 23:59:59");
            }else{
                /**时间格式化**/
                String endtime = customer.getAfterTime();
                if (!StringUtils.isEmpty(starttime) && !StringUtils.isEmpty(endtime)){
                    String timestart = starttime+" 00:00:00";
                    String timeend = endtime+" 23:59:59";
                    customer.setBeforeTime(timestart); customer.setAfterTime(timeend);
                }
            }
            /**人员或者时部门**/
            String users = customer.getMyCusCreator();
            List<String> listUsers = new ArrayList<>();
            if (!StringUtils.isEmpty(users)){
                List<String> uuidsArray = Arrays.asList(users.split(","));
                for (String uuid : uuidsArray){
                    if (uuid.contains("jpet")){
                        String deptid = uuid.replace("jpet","");
                        Example example = new Example(MyUser.class);
                        example.createCriteria().andEqualTo("deptId",deptid).andEqualTo("status","1");
                        List<MyUser> listall =  userMapper.selectByExample(example);
                        for (MyUser user:listall){
                            listUsers.add(user.getUserUuid());
                        }
                    }else{
                        listUsers.add(uuid);
                    }
                }
                customer.setMyCusList(listUsers);
            }
            /**执行查询**/
            List<MyCustomer> customers = mcsMapper.selectMyCuatomerList(customer);
            customers.forEach(myCustomer -> {
                AutonCusInfo.parsePerson(myCustomer,myuser);
            });
            return customers;
        }catch (Exception e){
            e.printStackTrace();
        }
        return new ArrayList<>();
    }

    @Override
    public List<MyCustomer> getMyPersonTimeAndUser(String starttime, String endtime, String userid) {
        try {
            Example example = new Example(MyCustomer.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andBetween("myCusCreatetime",starttime,endtime).andEqualTo("myCusCreator",userid);
            return this.selectByExample(example);

        }catch (Exception e){

        }
        return new ArrayList<>();
    }
}
